#!/bin/bash

# This file is part of libmarco
# http://code.google.com/p/libmarco/

# Automatic movements of files matching certain patterns to pre-defined 
# destination folders.
# I.e. move all jpg to pictures/ or all .avi to movies/
# See rules at the bottom

GREEN="\033[4;32m"
RED="\033[0;31m"
ORANGE="\033[0;34m"
NORM="\033[0m"

function print_args () {
	local i=0;
	while [[ $1 != "" ]]; do
		let 'i += 1';
		echo "[$i] \"$1\"";
		shift;
	done
}

function error_msg () {
	echo
	echo -e "${RED}error: ${$1}${NORM}"
	echo
}

function attention_msg () {
	echo -e " ${GREEN}${1}${NORM} "
}

function confirm_move () {
	local shortname=`basename $1`
	local msg="Move ${ORANGE}${shortname}${NORM}? [y/n]"
	echo -e $msg
	
	local valid="false"
	while [[ $valid == "false" ]]; do
		local valid="true"
		echo -n ">"
		read answer
		if [[ $answer == "n" ]]; then
			echo "File skipped"
		elif [[ $answer == "y" || $answer == "" ]]; then
			mv -i "$1" "$2"
			echo "File MOVED"
		else
			local valid="false"
			echo "What? \"$answer\""
		fi
	done
}


function automove () {
	# print_args "automove" $*
	
	# Read destination and check that it is a directory
	local destination="$1";
	shift
	if [[ ! -d $destination ]]; then
		error_msg "Invalid destination: $destination"
		return
	fi
	local sname=`basename $destination`
	attention_msg " -> $sname <-"
	
	while [[ "$1" != "" ]]; do
		
		if [[ ! -e "${1}" ]]; then
			echo "No match"
			return
		fi
		
		confirm_move "$1" $destination
		shift;
	done
	
	echo;
}

function multimove () {
	echo
	
	local sname;
	local destination="$1";
	if [[ ! -d $destination ]]; then
		error_msg "Invalid destination: $destination"
		return
	fi

	local src="$2";
	if [[ ! -d $src ]]; then
		error_msg "Invalid src: $src"
		return
	fi
	
	echo -n "Destination: "
	sname=`basename $destination`
	attention_msg "$sname"
	
	# save and change IFS
	OLDIFS=$IFS
	IFS=$'\n' 
	# read all file name into an array
	fileArray=($(find $src -maxdepth 1))
	# restore it
	IFS=$OLDIFS

	tLen=${#fileArray[@]}
	for (( i=0; i<${tLen}; i++ )); do
		# echo "${fileArray[$i]}"
		sname=`basename "${fileArray[$i]}"`
		echo " $i  -> $sname"
	done
	
	echo -n ">>>"
	read SELECTION;
	for s in $SELECTION; do
		# echo "mv ${fileArray[$s]} $destination/"
		sname=`basename "${fileArray[$s]}"`
		echo "moved: $sname"
		mv "${fileArray[$s]}" "$destination/"
		
	done
}

PICS="/Volumes/DataDisk/Pictures/"
PCAST="/Volumes/DataDisk/Podcasts/"


# automove <dst_dir> <expression>
# The second argument is expanded to a list of paths
# automove asks whether to move each one of them to dst_dir
# (enter == yes)
automove $PICS $HOME/Camera/*.jpg
automove $PCAST $HOME/Downloads/*.mp4

# multimove <dst_dir> <src_dir> 
# presents the list of items directly under src_dir (dirs or files, 
# no recursion) in a numbered list.
# Different indexes can be selected and the corresponding items will 
# be moved to dst_dir
multimove $HOME/.Trash/ $NEW
